package com.lxy.user.service.impl;

import com.lxy.common.JsonResult;
import com.lxy.user.dao.LagouTokenDao;
import com.lxy.user.pojo.LagouToken;
import com.lxy.user.service.LagouCodeServiceFeginClient;
import com.lxy.user.service.LagouTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;
import java.util.UUID;

/**
 * @author 123
 * @date 2020/6/28 11:16
 * @description
 */
@Service
@Transactional
public class LagouTokenServiceImpl implements LagouTokenService {


    @Autowired
    private LagouTokenDao lagouTokenDao;
    @Autowired
    private LagouCodeServiceFeginClient lagouCodeServiceFeginClient;


    @Override
    public JsonResult register(String email, String password, String code) {
        if(isRegistered(email)){
            return JsonResult.error("请不要重复注册");
        }
        JsonResult jsonResult=lagouCodeServiceFeginClient.authCode(email, code);
        if (!"200".equals(jsonResult.getCode())) {
            return jsonResult;
        }
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setPassword(password);
        lagouTokenDao.save(lagouToken);
        int i=0;
        int j =10/i;
        return JsonResult.ok("注册成功");
    }

    @Override
    public boolean isRegistered(String email) {
        return lagouTokenDao.findTopByEmail(email).isPresent();
    }

    @Override
    public JsonResult login(String email, String password) {
        Optional<LagouToken> topByEmial = lagouTokenDao.findTopByEmail(email);
        if(!topByEmial.isPresent() ){
            return JsonResult.error("账户不存在");
        }
        if (password.equals(topByEmial.get().getPassword())) {
            String token = UUID.randomUUID().toString();
            LagouToken lagouToken = topByEmial.get();
            lagouToken.setToken(token);
            lagouTokenDao.save(lagouToken);
            return JsonResult.ok(lagouToken);
        }
        return JsonResult.error("账户或者密码不正确");
    }

    @Override
    public JsonResult authToken(String token) {
        Optional<LagouToken> topByToken = lagouTokenDao.findTopByToken(token);
        if (topByToken.isPresent()) {
            return JsonResult.ok("success");
        }
        return JsonResult.error("fail");
    }
}
